<template>
  <div class="community-container">
    <div class="community-header">
      <h1>社区交流</h1>
      <el-button type="primary" @click="goToCreatePost" v-if="userStore.token">
        <el-icon><plus /></el-icon>发布新帖子
      </el-button>
    </div>

    <div class="filter-bar">
      <el-radio-group v-model="currentFilter" @change="handleFilterChange">
        <el-radio-button label="latest">最新</el-radio-button>
        <el-radio-button label="hot">热门</el-radio-button>
        <el-radio-button label="recommend">推荐</el-radio-button>
      </el-radio-group>
      
      <el-input
        v-model="searchKeyword"
        placeholder="搜索帖子"
        class="search-input"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><search /></el-icon>
        </template>
      </el-input>
    </div>

    <div class="post-list" v-loading="loading">
      <el-empty description="暂无帖子" v-if="posts.length === 0 && !loading"></el-empty>
      
      <el-card v-for="post in posts" :key="post.id" class="post-card" @click="viewPostDetail(post.id)">
        <div class="post-header">
          <div class="user-info">
            <el-avatar :size="40" :src="post.author.avatar"></el-avatar>
            <span class="username">{{ post.author.username }}</span>
          </div>
          <span class="post-time">{{ formatTime(post.createTime) }}</span>
        </div>
        
        <h3 class="post-title">{{ post.title }}</h3>
        <p class="post-content">{{ post.content }}</p>
        
        <div class="post-footer">
          <div class="post-stats">
            <span class="stat-item">
              <el-icon><view /></el-icon>
              {{ post.viewCount }}
            </span>
            <span class="stat-item">
              <el-icon><chat-dot-round /></el-icon>
              {{ post.commentCount }}
            </span>
            <span class="stat-item">
              <el-icon><star /></el-icon>
              {{ post.likeCount }}
            </span>
          </div>
          <div class="post-tags">
            <el-tag v-for="tag in post.tags" :key="tag" size="small">{{ tag }}</el-tag>
          </div>
        </div>
      </el-card>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPosts"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/userStore';
import { Plus, Search, View, ChatDotRound, Star } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();

// 状态变量
const loading = ref(false);
const posts = ref([]);
const currentFilter = ref('latest');
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalPosts = ref(0);

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true;
  try {
    // 这里是模拟数据，实际项目中应该调用API
    setTimeout(() => {
      const mockPosts = Array(10).fill().map((_, index) => ({
        id: index + 1,
        title: `帖子标题 ${index + 1}`,
        content: `这是帖子内容的简短描述，点击查看完整内容。这是帖子 ${index + 1} 的内容。`,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)),
        author: {
          id: Math.floor(Math.random() * 100),
          username: `用户${Math.floor(Math.random() * 1000)}`,
          avatar: `https://placekitten.com/200/200?image=${Math.floor(Math.random() * 16)}`
        },
        viewCount: Math.floor(Math.random() * 1000),
        commentCount: Math.floor(Math.random() * 50),
        likeCount: Math.floor(Math.random() * 100),
        tags: ['话题' + Math.floor(Math.random() * 5), '分类' + Math.floor(Math.random() * 3)]
      }));
      
      posts.value = mockPosts;
      totalPosts.value = 100; // 模拟总数
      loading.value = false;
    }, 500);
    
    // 实际API调用应该类似：
    // const response = await request.get('/api/posts', {
    //   params: {
    //     page: currentPage.value,
    //     pageSize: pageSize.value,
    //     filter: currentFilter.value,
    //     keyword: searchKeyword.value
    //   }
    // });
    // posts.value = response.data;
    // totalPosts.value = response.total;
  } catch (error) {
    console.error('获取帖子列表失败:', error);
    ElMessage.error('获取帖子列表失败');
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 查看帖子详情
const viewPostDetail = (postId) => {
  router.push(`/post/${postId}`);
};

// 创建新帖子
const goToCreatePost = () => {
  router.push('/create-post');
};

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1;
  fetchPosts();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchPosts();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchPosts();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchPosts();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchPosts();
});
</script>

<style scoped>
.community-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.community-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.post-list {
  margin-top: 20px;
}

.post-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.2s;
}

.post-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-weight: 500;
}

.post-time {
  color: #909399;
  font-size: 0.9rem;
}

.post-title {
  margin: 10px 0;
  font-size: 1.2rem;
}

.post-content {
  color: #606266;
  margin-bottom: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.post-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
}

.post-tags {
  display: flex;
  gap: 5px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style>